<template>
  <div :class="`tw-libfriendlinks x${_uid}`" ref="friendlinks">
    <template v-if="data.length > 0">
      <a class="tw-friendlink" v-for="(item, index) in nowdata" :key="index"
        :href="item.href"
        :target="item.target || '_self'"
        @click="clickLink(item)">
        <!-- <img class="xicon"
          :style="{height:iconHeight, marginBottom: marginIcon}"
          v-if="getIcons('default')"
          :src="`${$twApp.fileBaseUrl}${getIcons('default').localPath}`" />
        <img class="xhovericon"
          :style="{height:iconHeight, marginBottom: marginIcon}"
          v-if="getIcons('hover')"
          :src="`${$twApp.fileBaseUrl}${getIcons('hover').localPath}`" /> -->
          <span>{{item.text}}</span>
        <!-- <img
          :style="{height:iconHeight, marginBottom: marginIcon}"
          v-if="rightIcons.length > 0"
          :src="`${$twApp.fileBaseUrl}${getIcons('right').localPath}`" /> -->
      </a>
      <a class="tw-friendlink js-otherlinks" v-show="curIndex < data.length">
        <span>更多</span>
        <img class="xhovericon"
          :style="{height:iconHeight, marginBottom: marginIcon}"
          v-if="getIcons('hover')"
          :src="`${$twApp.fileBaseUrl}${getIcons('hover').localPath}`" />
        <img
          :style="{height:iconHeight, marginBottom: marginIcon}"
          v-if="rightIcons.length > 0"
          :src="`${$twApp.fileBaseUrl}${getIcons('right').localPath}`" />
      </a>
    </template>

    <tw-poppane
      class="xotherlinks"
      :placement="placement"
      switch=".js-otherlinks">
        <div :class="`tw-friendlink_more x${_uid}`">
          <a class="tw-friendlink" v-for="(item, index) in moredata" :key="index"
            :href="item.href"
            :target="item.target || '_self'"
            @click="clickLink(item)">
            <span>{{item.text}}</span>
          </a>
        </div>
    </tw-poppane>
  </div>
</template>

<script>
import props from './props'

export default {
  name: 'header-navigate',

  props,

  data() {
    return {
      collapsed: true,
      nowdata: [],
      moredata: [],
      curIndex: this.data.length,
      widthList: []
    }
  },

  computed: {
    style () {
      return {
        lineHeight: this.lineHeight,
        letterSpacing: this.letterSpacing,
        fontFamily: this.fontFamily,
        fontSize: this.fontSize,
        fontWeight: this.fontWeight ? '700' : '400',
        color: this.color,
        hoverColor: this.hoverColor,
        shadow: this.shadow,
        shadowSize: this.shadowSize,
        textAlign: this.align,
        iconOffsetTop: this.iconOffsetTop,
        paddingSet: this.paddingSet,
        backgroundColor: this.backgroundColor
      }
    }
  },

  methods: {
    init () {
      this.nowdata = []
      this.moredata = []
      this.data.forEach((item, index) => {
        if (index >= this.curIndex) {
          this.moredata.push({ ...item })
        } else {
          this.nowdata.push({ ...item })
        }
      })
    },
    getIcons (type) {
      if (type === 'right') {
        return this.rightIcons[0]
      } else if (type === 'default') {
        return this.icons[0]
      } else {
        return this.hoverIcons[0] || this.icons[0]
      }
    },

    setStyle () {
      let style = `
        ::root .tw-friendlink {
          line-height: ${this.lineHeight};
          font-family: ${this.fontFamily};
          font-size: ${this.fontSize};
          font-weight: ${this.style.fontWeight};
          color: ${this.color};
          text-align: ${this.align};
          padding: ${this.paddingSet};
          background-color: ${this.backgroundColor};
        }

        ::root .tw-friendlink:hover {
          color: ${this.hoverColor};
        }

        ::root.tw-libfriendlinks .tw-friendlink {
          margin: ${this.marginSet};
        }

        .tw-friendlink_more {
          width: ${this.widthMore};
          padding: ${this.paddingMore};
        }
        .tw-friendlink_more .tw-friendlink {
          line-height: ${this.lineHeight};
          font-family: ${this.fontFamily};
          font-size: ${this.fontSize};
          font-weight: ${this.style.fontWeight};

          padding: ${this.paddingMoreSet};
          margin: ${this.marginMoreSet};
          width: ${this.widthMoreSet};
          background-color: ${this.bgColorMore};
          color: ${this.colorMore};
        }
        .tw-friendlink_more .tw-friendlink:hover {
          background-color: ${this.bgColorMoreHigh};
          color: ${this.colorMoreHigh};
        }
      `

      if (this.letterSpacing) {
        style += `
          ::root .tw-friendlink {
            letter-spacing: ${this.letterSpacing};
          }
        `
      }

      if (this.iconOffsetTop) {
        style += `
          .tw-friendlink > .xicon {
            position: relative;
            margin-right: ${this.iconSpacing || 0};
            top: ${this.iconOffsetTop}
          }
        `
      }

      if (this.shadow) {
        style += `
          ::root .tw-friendlink {
            text-shadow: ${this.shadow ? `${this.shadowSize} ${this.shadow}` : 'none'};
          }
        `
      }

      if (this.enableMultLine) {
        style += `
          ::root.tw-libfriendlinks {
            flex-wrap: wrap;
          }
        `
      }

      if (this.hiddenMoreItem) {
        style += `
        .tw-friendlink_more .tw-friendlink {
          text-overflow: ellipsis;
          overflow: hidden;
          }
        `
      }

      this.addStyle(style)
    },

    addStyle (style) {
      this.$el.classList.add(`x${this._uid}`)
      const styleEl = document.getElementById(this._uid) || document.createElement('style')
      styleEl.id = this._uid
      styleEl.innerText = style.replace(/::root/gm, `.x${this._uid}`).replace(/\n/gm, '')

      document.head.appendChild(styleEl)
    },

    clickLink (e) {
      if (typeof this.clickFn === 'function') {
        e.preventDefault()
        this.clickFn(item)
      }
    },
    resize () {
      // this.curIndex = this.data.length
      // this.init()
      // this.$forceUpdate()
      let parentwidth = this.$refs.friendlinks.parentNode.offsetWidth
      let childwidth = 0
      let ctn = true
      this.widthList.forEach((item, index) => {
        childwidth += item
        if (ctn && childwidth >= parentwidth) {
          this.curIndex = (index - 1)
          ctn = false
        }
      })
      // this.$refs.friendlinks.childNodes.forEach((item, index) => {
      //   if (item instanceof HTMLElement) {
      //     childwidth += (item.offsetWidth ? item.offsetWidth : 0)
      //     let marginLeft = parseInt(window.getComputedStyle(item).marginLeft)
      //     let marginRight = parseInt(window.getComputedStyle(item).marginRight)
      //     childwidth += (marginLeft + marginRight)

      //     if (ctn && childwidth >= parentwidth) {
      //       // console.log('index', index)
      //       this.curIndex = (index - 1)
      //       ctn = false
      //     }
      //     // console.log('item', item)
      //     // console.log('offsetWidth', childwidth)
      //   }
      // })

      this.init()
    }
  },

  mounted () {
    this.setStyle()
    this.curIndex = this.data.length
    this.init()
    if (this.useMorePopper) {
      this.widthList = []
      this.$nextTick(() => {
        this.$refs.friendlinks.childNodes.forEach((item, index) => {
          if (item instanceof HTMLElement) {
            let offsetWidth = item.offsetWidth ? item.offsetWidth : 0
            let marginLeft = parseInt(window.getComputedStyle(item).marginLeft)
            let marginRight = parseInt(window.getComputedStyle(item).marginRight)
            this.widthList.push((offsetWidth + marginLeft + marginRight))
          }
        })
      })

      this.$nextTick(() => {
        this.resize()
      })
      window.addEventListener('resize', this.resize)
    }
  },

  beforeDestroy () {
    if (this.useMorePopper) {
      window.removeEventListener('resize', this.resize)
    }
  },

  watch: {
    data: {
      deep: true,
      handler () {
        this.curIndex = this.data.length
        if (this.useMorePopper) {
          this.curIndex = this.data.length
          this.init()

          this.widthList = []
          this.$nextTick(() => {
            this.$refs.friendlinks.childNodes.forEach((item, index) => {
              if (item instanceof HTMLElement) {
                let offsetWidth = item.offsetWidth ? item.offsetWidth : 0
                let marginLeft = parseInt(window.getComputedStyle(item).marginLeft)
                let marginRight = parseInt(window.getComputedStyle(item).marginRight)
                this.widthList.push((offsetWidth + marginLeft + marginRight))
              }
            })
          })

          this.$nextTick(() => {
            this.resize()
          })
        } else {
          this.init()
        }
      }
    },
    style: {
      deep: true,
      handler () {
        this.setStyle()
      }
    }
  }
}
</script>

<style lang="scss">
  @import './css/index.scss';
</style>
